package com.LC.Service;

import com.LC.Entity.Permission;
import com.LC.Entity.Role;
import com.LC.Entity.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
@Transactional
public class SpringSecurityUserService implements UserDetailsService {
    
    //通过dubbo远程调用服务
    @Reference
    UserService userService;

    /**
     * 根据用户名查询数据库获取用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User byUsername = userService.findByUsername(username);
        if (byUsername == null) {
          //用户不存在
          return null;
        }
        Set<Role> roles = byUsername.getRoles();
        List<GrantedAuthority> authorityList = new ArrayList<>();
        //遍历角色集合，为用户授予角色
        for (Role role : roles) {
            authorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                authorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));    
            }
        }
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username, byUsername.getPassword(), authorityList);
        
        return securityUser;
    }
}
